package com.example.learnapp;

import android.os.Bundle;
import android.os.Handler;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class Handle_Activity extends AppCompatActivity {

    private TextView text_view = null;
    private Button start = null;
    private Button end = null;

    //使用handler时首先要创建一个handler
    Handler handler = new Handler();
    //要用handler来处理多线程可以使用runnable接口，这里先定义该接口
    //线程中运行该接口的run函数

    private static int handler_type = 0;
    Runnable update_thread = new Runnable()
    {
        public void run()
        {
            handler_type++;
            //线程每次执行时输出"UpdateThread..."文字,\n为自动换行
            //text_view.append("\nUpdateThread..."+handler_type);
            //延时1s后又将线程加入到线程队列中
            handler.postDelayed(update_thread, 10);

            refreshLogView("\nUpdateThread..."+handler_type);


        }
    };

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handle);

        text_view = (TextView)findViewById(R.id.handle_tx);
        start = (Button)findViewById(R.id.handle_start);
        start.setOnClickListener(new StartClickListener());
        end = (Button)findViewById(R.id.handle_end);
        end.setOnClickListener(new EndClickListener());

        text_view.setMovementMethod(ScrollingMovementMethod.getInstance());
    }
    void refreshLogView(String msg){
        text_view.append(msg);
        int offset=text_view.getLineCount()*text_view.getLineHeight();
        if(offset>text_view.getHeight()){
            text_view.scrollTo(0,offset-text_view.getHeight());
        }
    }

    private class StartClickListener implements View.OnClickListener
    {
        public void onClick(View v) {
            // TODO Auto-generated method stub
            //将线程接口立刻送到线程队列中
            handler.post(update_thread);
        }
    }

    private class EndClickListener implements View.OnClickListener {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            //将接口从线程队列中移除
            handler.removeCallbacks(update_thread);
        }
    }


    }